package com.ledou44.ledourpc.clienthandler;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.ReadTimeoutHandler;
import io.netty.handler.timeout.WriteTimeoutHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author ledou44
 * 超时就抛出异常的服务初始化
 */
public class ClientHandler extends ChannelInitializer<SocketChannel>{

    /**
     * 处理业务的handler
     */
    private final ChannelHandlerAdapter channelHandlerAdapter;

    private final Integer type;

    /**
     * @param type 0：有超时检测（用于单次会话） 1：无超时检测（用于多次会话）
     */
    public ClientHandler(ChannelHandlerAdapter channelHandlerAdapter, Integer type) {
        this.channelHandlerAdapter = channelHandlerAdapter;
        this.type = type;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline().addLast(new StringDecoder());
        ch.pipeline().addLast(new StringEncoder());
        ch.pipeline().addLast(channelHandlerAdapter);
        if(type == 0) {
            //写入超时 在设置时间内没有写入操作
            ch.pipeline().addLast(new WriteTimeoutHandler(5000, TimeUnit.MILLISECONDS));
            //读取超时 在设置时间内没有读取操作
            ch.pipeline().addLast(new ReadTimeoutHandler(5000, TimeUnit.MILLISECONDS));
        }
    }
}
